<!-- <script type="text/javascript" src="/static/amrPlayer-jsdemo/voice-2.0.js"></script> -->
<script type="text/javascript" src="/static/amrPlayer-jsdemo/BenzAMRRecorder.js"></script>
<!-- <link href="/static/video-js-5.20.1/video-js.css" rel="stylesheet">
<script src="/static/video-js-5.20.1/video.js"></script> -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/video.js/7.8.1/video-js.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/video.js/7.8.1/video.min.js"></script>
<style> 
/*#trail_detail_list{ position:absolute; left:400px; bottom:0px; background:#FFFFFF; width:50%;height:300px }*/
#showtml{ position:absolute; left:30px; top:80px; background:#FFFFFF; width:100px;}
/*#chat_interact{ position:absolute; left:0px; top:80px; }*/
#time_tool { position:absolute; left:10px; top:10px; background:#FFFFFF; width:100%;}

.BMap_cpyCtrl {
display:none !important;
}
.anchorBL{
display:none !important;
}

</style> 
<div id="allmap" class ="baidu-maps" style="width: 100%;height: 100%"></div> 
<!-- <div style="position: absolute;right: 100px;top: 80px;width: 400px;height: 400px;background-color: white">
</div> -->
<div id="time_tool" style="color:white;background-color:rgba(320,138,138,0)">
  <form class="layui-form layui-form-pane " action="" id="trail_query_form" lay-filter="trail_query_form">
    <div class="layui-form-item" style="color:black">
      <div class="layui-inline">
        <div class="layui-input-inline" >
          <select id="tml_list" name="device_id"  lay-verify="required" lay-search="" class="layui-input" placeholder="">
          </select>
        </div>
        <div class="layui-form-mid layui-word-aux">—</div>
        <a class="layui-btn" id="" lay-submit="" lay-filter="trail_query"><i class="layui-icon layui-icon-search" style="font-size: 15px"></i></a>
        <a class="layui-btn" id="start_interact"><i class="fa fa-play" style="font-size: 12px"></i></a>
        <!-- <a class="layui-btn" id="pause"><i class="fa fa-pause" style="font-size: 12px"></i></a> -->
        <a class="layui-btn" id="stop_interact"><i class="fa fa-stop" style="font-size: 12px"></i></a>
      </div>
    </div>
  </form>
</div>

<div id="chat_interact" style="padding: 2px;background-color:#F2F2F2 ;display: none;">
  <div class="layui-card">
    <div class="layui-card-body" style="">
      <!-- 交互内容显示窗口start -->
      <div id="chat_content_panle" class="layui-col-md12" style=" ">
        <div id="video_show_panal" style="display: none;margin: 0">
        <video id="video" class="video" style="" ></video>
        <button class="layui-btn layui-btn-xs" id="video_stop" style="margin: -70px 0px 0px 77%;position: relative;z-index: 999;">关闭</button>
        <video id="video1" class="video" style="width: 400px;margin:0px 0px 0px 0px;display: none;" class="video-js vjs-default-skin">
          <!-- <source src="http://139.199.9.116:80/hls/test1.m3u8" type="application/x-mpegURL"> -->
        </video>
        </div>
      </div>
      <!-- 交互内容显示窗口end --> 
      <div class="layui-row">
        <div class="layui-col-md10">
          <div class="layui-btn-group" style="margin: 0px 2px -50px;position: relative;z-index: 999">
            <button type="button" class="layui-btn layui-btn-xs" id="chat_text">
              <i class="layui-icon ">&#xe642;</i>字
            </button>
            <button type="button" class="layui-btn layui-btn-xs" id="chat_picture">
              <i class="layui-icon ">&#xe65d;</i>图
            </button>
            <button type="button" class="layui-btn layui-btn-xs" id="chat_voice">
              <i class="layui-icon">&#xe645;</i>音
            </button>
            <button type="button" class="layui-btn layui-btn-xs" id="chat_video">
              <i class="layui-icon">&#xe6ed;</i>视
            </button>
            <button type="button" class="layui-btn layui-btn-xs" id="chat_commd">
              <i class="layui-icon">&#xe602;</i>其他
            </button>
          </div>
        </div>
        <div class="layui-col-md2" style="margin: 1px 75% -50px;position: relative;z-index: 999">
          <button type="button" class="layui-btn layui-btn-xs" id="chat_history">
              <i class="layui-icon">&#xe611;</i>历史记录
            </button>
        </div>
      </div>
      <div contentEditable="true" id="chat_input_panle" class="layui-col-md12" style="">
        
      </div>
      <div class="layui-btn-group" style="margin: -55px 0px 0px 75%;position: relative;z-index: 999">
        <button type="button" class="layui-btn layui-btn-xs" onclick="show_hide_chat_panle('hide')">
          关闭
        </button>
        <button type="button" class="layui-btn layui-btn-xs" id="chat_send_btn">
          发送
        </button>
      </div>
    </div>
  </div>
 
</div>
<button id="chat_sw" class="layui-btn" onclick="show_hide_chat_panle('show')" style="position: absolute;left: -20px;top: 40%;height: 150px;width: 10px;display: none;"><i class="layui-icon">&#xe66b;</i></button>

<!-- 命令下发表格的执行按钮 -->
<script type="text/html" id="command_table_bar">
    <a class="layui-btn layui-btn-xs" lay-event="excue_command">执行</a>
</script>
<form  class="layui-form layui-form-pane " action="" id="command_form" lay-filter="command_form" style="padding: 5px;display: none;">
  <table class="layui-table" id="command_down_table" lay-size="xs" lay-filter="command_table_filter">
  </table>
</form>
<!-- 命令下发弹窗结束 -->

<!-- chat历史数据查询时间选择start -->

<form  class="layui-form layui-form-pane " action="" id="query_time_form" lay-filter="query_time_form" style="padding: 5px;display: none;">
  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">查询时间段</label>
      <div class="layui-input-inline">
        <input id="chat_history_time" type="text" name="chat_history_time"  lay-verify="required" placeholder="查询时间段" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">类别</label>
      <div class="layui-input-inline">
        <select name="kind" xm-select="query_kind" xm-select-type="1" xm-select-height="36px">
          <option value="text">文字</option>
          <option value="voice">语音</option>
          <option value="img">图像</option>
        </select>
      </div>
    </div>
  </div>
  <button id="query_time_btn" lay-submit lay-filter="query_time_form" style="display: none;">提交</button>
</form>

<!-- chat历史数据查询时间选择end -->

<script type="text/javascript">

//----chat窗口css调整，展示start----//

var chat_p;
var chat_p_w=get_width/4
var chat_p_h=get_height-315
var chat_content_h=chat_p_h/2
var chat_input_h=chat_p_h-chat_content_h-60
$('#chat_content_panle').attr('style','height:'+chat_content_h+'px;padding:0;margin: 0px 0px -25px;border:1px solid #F2F2F2;overflow: auto;background-color:#F2F2F2')
$('#chat_input_panle').attr('style','height: '+chat_input_h+'px;padding: 30px 0px 30px 10px;border:1px solid #F2F2F2;outline: none;overflow: auto;;background-color:#F2F2F2')
var show_hide_chat_panle=function(commd,dev=''){
  if(commd=='hide'){
    $('#chat_sw').show()
    layer.close(chat_p)
  }else if(commd=='show'){
    $('#chat_sw').hide()
    chat_p=layer.open({
      type: 1
      ,title:'实时交互：'+chosed_dev.user_name
      ,area:[''+get_width/4+'px',''+get_height-290+'px']
      ,offset:['120px','0px']  
      ,id: 'chat_interact_panle' //防止重复弹出
      ,content:$('#chat_interact')
      ,shade: 0 //不显示遮罩
      ,cancel:function(layero,index){
        $('#chat_sw').show()
      }
    });
  }
}
//----chat窗口css调整，展示end----//


// chat窗口内容填充函数
var fill_chat_panle=function(content,kind,send_time,div_width,div_dom,position){


  var chat_content_show;

  if(kind=='picture' | kind=='img'){
    chat_content_show='<img src='+content+' style="width:'+div_width/5+'px;position:relative;margin:0 0 0 10px">'
    if(position=='right'){
      chat_content_show='<img src='+content+' style="width:'+div_width/5+'px;position:absolute;right:10px;">'
    }
    
  }else if(kind=='voice' | kind=='voice'){
    if(content){
      var amr = new BenzAMRRecorder();
      amr.initWithUrl(content).then(function(){})
      var data_length= amr.getDuration().toFixed(2) + '\'';
      chat_content_show='<button id='+chosed_dev.device_id+send_time+' class="layui-btn layui-btn-sm" onclick="play_amr_file(\''+content+'\')">'+data_length+'S <i class="layui-icon layui-icon-voice" ></i></button>'
      if(position=='right'){
        chat_content_show='<button style="position:absolute;right:10px;" id='+chosed_dev.device_id+send_time+' class="layui-btn layui-btn-sm" onclick="play_amr_file(\''+content+'\')">'+data_length+'S <i class="layui-icon layui-icon-voice" ></i></button>'
      }
    }else{
      layer.msg('请录音')
    }  
  }else{
    chat_content_show='<table class="" style="background-color:#5FB878;position:absolute;'+position+':10px;border-radius:5px">'+
                        '<td style="word-break:break-all;padding:5px">'+content+'</td>'+
                        '</table>'
    
  }
  var chat_content_style;
  if(position=='right'){
    chat_content_style=
                    '<div class="row" style="position:relative;right:10px;padding:10px;margin:0 0 10px 10%">'+
                      '<p style="text-align:right;font-size:10px;">'+send_time+'</p>'+
                      '<div class="layui-col-md10">'+
                        chat_content_show+
                      '</div>'+
                      '<div class="layui-col-md2" style="position:absolute;right:10px">'+
                      '<img src="'+user_icon+'" style="width:'+div_width/10+'px;height:'+div_width/10+'px;border-radius:15px">'+
                      '</div>'+
                    '</div>'+
                    '<br>'
  }else{
  chat_content_style='<div class="row" style="padding:10px;margin:10px;border-radius:5px">'+
                  '<p style="font-size:10px;">'+send_time+'</p>'+
                  '<div class="layui-col-md2" >'+
                    '<img src="/static/img/person_default.png" style="width:'+div_width/10+'px;height:'+div_width/10+'px;">'+
                  '</div>'+
                  '<div class="layui-col-md10">'+
                  chat_content_show+
                  '</div>'+
                '</div>'+
                '<br>'
  }
  
    
  // $('#chat_content_panle').append()
  div_dom.append(chat_content_style)
  // 自动滚动到最下方
  div_dom.scrollTop(div_dom.offset().top+div_dom.scrollTop())
}


var play_amr_file=function(amr_path){
  var amr = new BenzAMRRecorder();
  amr.initWithUrl(amr_path).then(function() {
    // amr.isPlaying() 返回音频的播放状态 是否正在播放 返回boolean类型
    data_length= amr.getDuration().toFixed(2) + '\'';
    console.log(amr.isPlaying(),data_length)
    if(amr.isPlaying()){
      amr.stop();
    } else {
      amr.play();
    }
  });

}

//----chat窗口历史数据查询start----//

//默认点击一次查询3天,暂时不用，要做点击一次加3天的数据，比较麻烦，后续在考虑
// $('#chat_history').click(function(){
//   console.log('chat_histort')
//   var s_time=$('#get_current_time').text()
//   // 转换时间格式，时间戳
//   e_time=new Date((new Date().getTime()/1000-3*3600*24)*1000)
//   e_time=e_time.toLocaleDateString().replace(/\//g, "-") + " " + e_time.toTimeString().substr(0, 8)
//   var param_data={'device_id':chosed_dev.device_id,'s_time':s_time,'e_time':e_time,'kind':['voice','text','img']}
//   console.log(param_data)
//   query_chat_history(param_data)
// })

//双击自定义查询
var chat_query_time_form;
$('#chat_history').click(function(){
  console.log('chat_histort')
  formSelects.render()
  chat_query_time_form=layer.open({
    type: 1
    ,title:'自定义查询'
    ,area:['400px','380px']
    ,offset:'l'  
    ,id: 'query_time_form_data' 
    ,content:$('#query_time_form')
    ,btn:'提交'
    ,shade: 0 //不显示遮罩
    ,btn1: function(){
      $('#query_time_btn').click()
      layer.close(chat_query_time_form)
    }
  }); 
})

form.on('submit(query_time_form)',function(obj){
  console.log(obj)
  // 替换的部分，第一位和最后一位有个空格
  var timedata=obj.field.chat_history_time.split(' - ')

  var s_time=timedata[0]
  var e_time=timedata[1]
  var query_kind=obj.field.kind.split(',')
  if(query_kind==''){
    query_kind=['voice','text','picture']
  }
  var param_data={'device_id':chosed_dev.device_id,'s_time':s_time,'e_time':e_time,'kind':query_kind}
  console.log(param_data)
  query_chat_history(param_data)
  return false
})

var query_chat_history=function(param_data){
  param_data=JSON.stringify(param_data)
  $.ajax({
    type: 'POST',
    data:{param_data},
    url:"/interact/?what="+"get_chat",
    async:true,
    dataType: 'json',
    success: function(mult_data) {
      console.log(mult_data)
      layer.msg('操作成功')
      $('#chat_content_panle').empty()
      for(var i=0;i<mult_data.length;i++){
        var content=mult_data[i].content
        var kind=mult_data[i].content_kind
        var send_time=mult_data[i].send_time
        var receiver=mult_data[i].receiver
        var position=''
        if(receiver==chosed_dev.device_id){
          position='right'
        }
        fill_chat_panle(content,kind,send_time,chat_p_w,$('#chat_content_panle'),position)
      }
    },
    error:function(obj){
       layer.msg('ajax操作失败')
       console.log(obj)
    }
  });
}

//----chat窗口历史数据查询end----//


// -----信息上传后台并且在content窗口展示start----//

dialog_talk={'voice':'TK','text':'MESSAGE','picture':'wdimg'}
var chat_upload_data;
var chat_upload_kind=null;
var all_voice_data={}
$("#chat_input_panle").empty()
$('#chat_send_btn').click(function(){

  var send_time=$('#get_current_time').text()
  var chat_content_show;
  if(chat_upload_kind=='picture'){
    chat_content_show='<img src='+chat_upload_data+' style="width:'+chat_p_w/5+'px">'
  }else if(chat_upload_kind=='voice'){
    if(chat_upload_data){
      v_data_id=send_time+chat_upload_data.len
      all_voice_data[v_data_id]=chat_upload_data.obj
      var voice_len=chat_upload_data.len
      chat_upload_data='v,'+chat_upload_data.data
      chat_content_show='<button id="'+v_data_id+'" class="layui-btn layui-btn-sm" onclick="play_voice(\''+v_data_id+'\')">'+voice_len+'S <i class="layui-icon layui-icon-voice" ></i></button>'
    }else{
      layer.msg('请录音')
    }  
  }else{
    chat_upload_kind='text'
    chat_upload_data=$('#chat_input_panle').text()
    chat_content_show=chat_upload_data
    
  }
  console.log('========>',chat_upload_data,$('#chat_input_panle').text())
  if(chat_upload_data==null | chat_upload_data==''){
    layer.msg('请输入内容')
    return false
  }

  // 传后台
  var param_data={'device_id':chosed_dev.device_id,'set_command':chat_upload_kind,'set_value':chat_upload_data,'send_time':send_time,
                  'port':chosed_dev.dynamic.receive_port}
  param_data=JSON.stringify(param_data)
  console.log(param_data)
  $.ajax({
    type: 'POST',
    data:{param_data},
    url:"/interact/?what="+"send_chat",
    async:true,
    dataType: 'json',
    success: function(data) {
      if(data!='set_param,ok!'){
        layer.msg('失败：'+data)
        return false
      }
      layer.msg('操作成功')
      chat_content_style='<div class="row" style="padding:10px;margin:10px">'+
                            '<p style="text-align:right;font-size:10px;">'+send_time+'</p>'+
                            '<div class="layui-col-md10">'+
                              '<table class="" style="background-color:#5FB878;position:absolute;right:10px;">'+
                              '<td style="word-break:break-all">'+chat_content_show+'</td>'+
                              '</table>'+
                            '</div>'+
                            '<div class="layui-col-md2" style="position:absolute;right:10px;border-radius:5px">'+
                            '<img src="'+user_icon+'" style="width:'+chat_p_w/10+'px;height:'+chat_p_w/10+'px;">'+
                            '</div>'+
                          '</div>'+
                          '<br>'

      // $('#chat_content_panle').append()
      $('#chat_content_panle').append(chat_content_style)
      // 自动滚动到最下方
      $('#chat_content_panle').scrollTop($('#chat_content_panle').offset().top+$('#chat_content_panle').scrollTop())

      chat_upload_data=null;
      chat_upload_kind=null;
      $("#chat_input_panle").empty()
    },
    error:function(obj){

       layer.msg('ajax操作失败')
       console.log(obj)
    }
  });
})

// ----信息上传后台并且在content窗口展示start----//

// ----文字信息上传start---- //

$('#chat_text').click(function(){
  $("#chat_input_panle").empty()
  $("#video_show_panal").hide()
  chat_upload_kind='text'

})

// ----文字信息上传end---- //

// ----图片上传start---- //

upload.render({
  elem: '#chat_picture'
  ,auto: false
  ,choose: function(obj){
    obj.preview(function(index, file, result){
      // result是图片 base64编码
      var img_content='<img src='+result+' style="width:auto;height:80px">'
      chat_upload_data=result
      $("#chat_input_panle").empty()
      $('#chat_input_panle').append(img_content)
      $("#video_show_panal").hide()
      chat_upload_kind='picture'
    });
  }
});

// ----图片上传end---- //

// -----音频处理start-----//

// RongIMLib.RongIMVoice.init();
var play_voice=function(voice){
  if(all_voice_data[voice]){
    voice=all_voice_data[voice]
    if(voice.isPlaying()){
      voice.stop()
    }else{
      voice.play()
    }
  }
}

var stop_recod=function(){
  amrForRecorder.finishRecord().then(() => {
    // amrForRecorder.play()
    voice_data=arrayBufferToBase64(amrForRecorder._rawData)
    
    var voice_obj= new BenzAMRRecorder()
    voice_obj.initWithArrayBuffer(amrForRecorder._rawData).then(function(){
      data_length= amrForRecorder.getDuration().toFixed(2) + '\'';
      chat_upload_data={'data':voice_data,'len':data_length,'obj': voice_obj}
      console.log(data_length)
    })
  });
}

var amrForRecorder;
var voice_data;
var recordBtn;

$('#chat_voice').click(function(){
  $("#chat_input_panle").empty()
  $("#video_show_panal").hide()
  var re_btn='<button class="layui-btn layui-btn-xs layui-btn-fluid" id="amr-record" style="margin:20px;width:80%;"></button>'
  $("#chat_input_panle").append(re_btn)
  recordBtn = $('#amr-record');
  recordBtn.text('点击开始录音')
  chat_upload_kind='voice'
  var cold_time;
  var play_btn
  var secs=0
  
  recordBtn.click(function () {
    var play_s=0
    if (amrForRecorder && amrForRecorder.isRecording()) {
        // recordBtn.html('正在录音（点击停止）');
        stop_recod()
    } else {
        // recordBtn.html('录音结束（点击开始）');
        if(recordBtn.text()=='点击开始录音'){
          amrForRecorder = new BenzAMRRecorder();
          amrForRecorder.initWithRecord().then(() => {
              amrForRecorder.startRecord();

          }).catch(function(e) {
              layer.alert(e.message || e.name || JSON.stringify(e));
          });
        }else if(recordBtn.text().slice(0,4)=='播放录音'){
          // play_voice(voice_data)
          amrForRecorder.play()

          // recordBtn.text('播放录音（'+secs+'S）');
          play_btn=setInterval(function(){
            recordBtn.text('正在播放（点击停止）（'+play_s+'S）')
            play_s=play_s+1
            console.log(secs,play_s)
            if(play_s==secs){
              recordBtn.text('播放录音（'+secs+'S）');
              play_s=0
              clearInterval(play_btn)
              return
            }
          },1000)
        }else if(recordBtn.text().slice(0,4)=='正在播放'){
          console.log('stop')
          amrForRecorder.stop()
          clearInterval(play_btn)
          recordBtn.text('播放录音（'+secs+'S）');
        }

        // 绑定事件
        amrForRecorder.onStartRecord(function () {
            console.log('Recorder Event: startRecord');
            // recordBtn.html('正在录音（点击停止）')
            cold_time=setInterval(function(){
              recordBtn.text('正在录音（点击停止）（'+secs+'S）')
              var red_icon='<i class="layui-icon layui-icon-circle-dot" id="voice_icon"></i>'
              recordBtn.append(red_icon)

              if(secs%2==0){
                $('#voice_icon').attr('style','color:black')
              }else{
                $('#voice_icon').attr('style','color:red')
              }
              
              if(secs==15){
                clearInterval(cold_time);
                stop_recod()
                return
              }
              secs=secs+1
            },1000)
        });
        amrForRecorder.onFinishRecord(function () {
            console.log('Recorder Event: finishRecord');
            recordBtn.text('播放录音（'+secs+'S）');
            clearInterval(cold_time);
        });
        amrForRecorder.onCancelRecord(function () {
            console.log('Recorder Event: cancelRecord');
            recordBtn.html('点击开始录音');
        });
    }
});

  
})


function arrayBufferToBase64(buffer) {
         var binary = '';
         var bytes = new Uint8Array(buffer);
         var len = bytes.byteLength;
         for (var i = 0; i < len; i++) {
               binary += String.fromCharCode(bytes[i]);
         }
         return window.btoa(binary);}

// -----音频处理end-----//

// -----视频处理start-----//
var video={'start':false};
var mediaRecorder={'start':false};
var call_dev={'start':false};
$('#chat_video').click(function(){
  layer.msg('设备不支持')
  return false
  if(video.start==true){
    layer.msg('video already start')
    return false
  }
  let constraints = {
          video: { width: 320, height: 200 ,frameRate:24,},
          audio: false
        };

  video = document.getElementById("video");
  $("#video_show_panal").show()

  let promise = navigator.mediaDevices.getUserMedia(constraints);

  promise.then(function(stream) {
    var options
    if (MediaRecorder.isTypeSupported('video/webm;codecs=vp9')) {
      options = {mimeType: 'video/webm;codecs=h264'};
    } else if (MediaRecorder.isTypeSupported('video/webm;codecs=h264')) {
      options = {mimeType: 'video/webm;codecs=h264'};
    } else  if (MediaRecorder.isTypeSupported('video/webm;codecs=vp8')) {
      options = {mimeType: 'video/webm;codecs=vp8'};
    }
    console.log('Using '+options.mimeType);
    mediaRecorder = new MediaRecorder(stream,options);
    
    mediaStream = stream;
    var chunks = [], startTime = 0,mesg_num=0;
    video.srcObject = stream;
    video.play();
    video.start=true
    // 摘出视频数据，通过websocket传给后台
    mediaRecorder.ondataavailable = function(e) {
      // console.log('Recorder',e.data)
      chunks.push(e.data);
      var reader = new FileReader();
      reader.addEventListener("loadend", function(e) {
        var buf =e.target.result;
        console.log(buf)
        buf=buf.split(',')[1]
        if(mesg_num !== 0){
          wsocket.send(buf)
          console.log(buf)
        }
        mesg_num==1
        // console.log(reader.result);    

      });
      reader.readAsDataURL(e.data);
    };
    
    // 发起呼叫
    pull_video('video_url')
    call_dev=setInterval(function(){
      startTime++
      if(startTime==1 && $('#call_dev_time').val()==null){
        var cdt='<button class="layui-btn layui-btn-primary layui-btn-sm" id="call_dev_time" style="margin: -225px 0px 0px 10%;position: relative;z-index: 999;width:70%">calling...('+startTime+')</button>'
        $('#video_show_panal').append(cdt)
      }else{
        $('#call_dev_time').show()
        $('#call_dev_time').text('calling...('+startTime+')')
      }
      if(startTime>30){
        pull_video('video_url','stop')
        $('#call_dev_time').hide()
        layer.msg('对方无反应，呼叫结束')
        $('#video_stop').click()
      }
    },1000)
    
    
  });
})

// 呼叫之后，设备有回应，可以进行视频通话，调用该函数
var video_talk=function(){
  var wsurl="ws://127.0.0.1:8000/interact/"
  wsocket = new WebSocket(wsurl);
  mediaRecorder.start(10)
  wsocket.start=true
  mediaRecorder.start=true
}


//videojs拉流,停止等
var dev_video={'start':false};
var pull_video=function(video_url,func='play'){
    // var video1=videojs('video1', {autoplay:true}, function(){video1.play();console.log('videojs播放器初始化成功')})
  if(func=='stop'){
    dev_video.pause()
    return false
  }
  if(dev_video.start==true){
    layer.msg('video already start')
    return false
  }
  video_url='rtmp://139.199.9.116:1935/jt808video/'+'test1'
  dev_video =  videojs("video1");  //初始化视频
  dev_video.src({
    src: video_url,
    type:'rtmp/flv'
  });
  dev_video.load();
  dev_video.ready(function(){
      dev_video.play();
      dev_video.start=true
  })
}

$('#video_stop').click(function(){
  if(video.start==true){
    video.pause()
    video.start=false
    clearInterval(call_dev)
    $("#video_show_panal").hide()
  }
  if(mediaRecorder.start==true){
    mediaRecorder.stop();
    mediaRecorder.start=false
  }
  if(wsocket.start==true){
    wsocket.send('stop')
    wsocket.close()
    wsocket.start=false
  }
  if(dev_video.start==true){
    pull_video('video_url','stop')
  }
})

// -----视频处理end-----//

// ------其他（即时命令下发） start------//

$('#chat_commd').click(function(){
  command_modal(chosed_dev.device_id)
})

var command_dict={'call_now':'实时点名','factory_set':'恢复出厂设置','verson_detail':'查询版本信息','dev_reset':'远程重启','turn_off_dev':'远程关机',
                  'find_dev':'设备寻找','monitor':'监听','photograph':'远程拍照','health_detect':'健康检测'}


var command_modal=function(device_id){
  // 重新组装可以加载到表格的命令数据格式
  // console.log(device_id)
    var command_detail=[]
    for(k in command_dict){
      var comm_value={};
      comm_value['command_style']=k
      comm_value['command_name']=command_dict[k]
      comm_value['device_id']=device_id
      command_detail.push(comm_value)

    }
   

  layer.open({
      type: 1
      ,title:'命令下发: '+device_id
      // ,area:'200px'
      ,offset:'l'  
      ,id: 'command_data' //防止重复弹出
      ,content:$('#command_form')
      ,shade: 0 //不显示遮罩
      ,success:function(layero,index){
          table.render({
          elem: '#command_down_table',
          data: command_detail,
          id:'command_down_table',
          skin:'nob',
          size:'sm',
          cols: [[
              {field: 'device_id', title: '设备ID',hide:true},
              {field: 'command_name',width:120, title: '名称',sort:true},
              {field: 'command_style', title: '命令格式',hide:true},
              {title: '操作',templet: '#command_table_bar', fixed: "right", align: "center"}
          ]],
          page: false
        });
      }
    });
};


//命令下发到后台进行处理
table.on('tool(command_table_filter)', function (obj) {
  if(chosed_dev.on_off_line!=='online'){
    layer.msg('设备离线，无法执行该指令')
    return false
  }
  var comm_result = obj.data;
  var send_time=$('#get_current_time').text()
  var param_data={'device_id':comm_result.device_id,'set_command':comm_result.command_style,'set_value':'1','send_time':send_time,
                  'port':chosed_dev.dynamic.receive_port}
  param_data=JSON.stringify(param_data)
  // console.log(param_data)
  $.ajax({
    type: 'POST',
    data:{param_data},
    url:"/dynamic/?what="+"order_dowm",
    async:true,
    dataType: 'json',
    success: function(data) {
      layer.msg('操作成功')
      // if(data=='set_param,ok!'){
        
      // }else{
      //    layer.msg('操作失败')
      // }
      // console.log(data)
    },
    error:function(obj){
       layer.msg('操作失败'+JSON.stringify(obj) )
    }
  });
});

// ------其他（即时命令下发） end------//
  

var add_dev_detail=function(gps){
  // console.log(gps)
  var bds_num=gps.dynamic.bds_num,param1,param2,param3,param4,blood_pres,gps_num=gps.dynamic.gps_num,rssi=gps.dynamic.rssi;
    var dev_kind='0'
    if(gps.dynamic.receive_port!='0'){
      dev_kind=gps.dynamic.receive_port[1]
    }
    var dev_loca=''
    // console.log(dev_loca)
    if(dev_loca=='' && gps.dynamic.track_type!=='0'){
      wifi_lbs={'wifi':gps.dynamic.wifi,'lbs':gps.dynamic.lbs}
      dev_loca='<button class="layui-btn layui-btn-xs" onclick="get_wifi_lbs_addr('+gps.device_id+',\''+gps.dynamic.track_type+'\')">点击解析'+gps.dynamic.track_type+'地址</button>'
    }

    // var status_list=['acc_off', 'ante_ok', 'undefence', 'normal','online','sleep']
    status_dict={'undefence':'未设防', 'normal':'正常','online':'在线','sleep':'休眠','sos_alarm':'SOS报警'}
    if(bds_num==null){
      bds_num='0'
    }
    if(gps_num==null){
      gps_num='0'
    }
    // var stop_time=(eval('('+gps.stop_time+')')['stop_time']/60).toFixed(0)
    var stop_time='0'
    var g_status;
    var status=''
    if(gps.on_off_line=='online'){
      g_status='1'
    }else{
      g_status='0'
    }
    // 状态信息
    for(var i=0;i<gps.status.length;i++){
      if(gps.status[i] in status_dict){
        status+=status_dict[gps.status[i]]+','
      }else{
        status+=gps.status[i]+','
      }
    }
    
    blood_pres=''
    if(gps.dynamic.blood_pres!='0'){
      blood_pres=eval('('+gps.dynamic.blood_pres+')')
      blood_pres='高：'+blood_pres['h_pres']+','+'低：'+blood_pres['l_pres']
    }
    heart_rate=''
    if(gps.dynamic.heart_rate!='0'){
      heart_rate=gps.dynamic.heart_rate
    }

    // 绑定的用户信息
    var user_detail=gps.user_detail;
    // if(user_detail!='0' | user_detail!=0){
    //   user_detail=gps.user_detail.current
    // }
    var dev_user_name=gps.user_name;
    var user_sex='',user_department='',user_character='',user_age='',user_picture='';
    if(user_detail!='0' | user_detail!=0){
      user_sex=user_detail.sex
      var person_detail=eval('('+user_detail.person_detail+')')
      user_department=person_detail.department
      user_character=person_detail.character
      user_age=person_detail.person_age
      user_picture=person_detail.picture
      dev_user_name=user_detail.name
    }
    if(user_picture==='' | user_picture==null){
      user_picture='/static/img/person_default.png'
    }
    var param1='性别：'+user_sex
    var param2='，年龄：'+user_age
    var param3='部门：'+user_department
    var param4='，职位：'+user_character

        //信息窗口参数
      var opts = {
        width : 470,     // 信息窗口宽度
        height: 450,     // 信息窗口高度
        };
      var info_window;
      info_window=
            '<div class="layui-row" style="height:300px";>'+
              '<div class="layui-col-md1" style="padding:2px;background-color: #F2F2F2;">'+
                '<div class="layui-card">'+
                  '<div class="layui-card-body">'+
                    '<img src="'+user_picture+'" style="width: 100px;height: 140px">'+
                  '</div>'+
                '</div>'+
              '</div>'+
              '<div class="layui-col-md2" style="padding:2px;background-color: #F2F2F2;">'+
                '<div class="layui-card">'+
                  '<div class="layui-card-body">'+
                    "<table class='layui-table' lay-size='sm' lay-skin='nob' style='font-size:13px;height: 140px';>"+
                      "<tr >"+
                      "<td ><font>"+"名称: "+dev_user_name+"</font></td>"+
                      "</tr>"+
                      "<tr>"+
                      "<td colspan=4>"+"设备ID:"+gps.device_id+"</td>"+
                      "</tr>"+
                      "<tr>"+
                      "<td >"+param1+param2+"</td>"+
                      "</tr>"+
                      "<tr>"+
                      "<td >"+param3+param4+"</td>"+
                      "</tr>"+
                      // "<tr>"+
                      // "<td colspan=2>"+" <i class='layui-icon layui-icon-console' aria-hidden='true' style='color:#1E9FFF'></i>："+gps.serv_receive+" ，<i class='fa fa-map-marker' aria-hidden='true' style='color:#5FB878'></i>："+gps.dynamic.track_type+"</td>"+
                      // "</tr>"+
                      // "<tr>"+
                      // "<td colspan=2>"+" <i class='fa fa-map' aria-hidden='true' style='color:#009688'></i>："+"</td>"+
                      // "</tr>"+
                      "</table>"+ 
                  '</div>'+
                '</div>'+
              '</div>'+
              '<div class="layui-col-md9" style="background-color: #F2F2F2;padding:2px">'+
                '<table id="interact_detail_table" lay-filter="interact_detail_table" class="layui-table" style="padding:0px;margin:-5px"></table>'+
              '</div>'+
            '</div>'
    ;
    $('.layui-footer').empty()
    $('.layui-footer').append(info_window)


};


var interact_table=function(d){
  table.render({
            elem: '#interact_detail_table',
            data: d,
            id:'interact_detail_table',
            skin:'nob',
            size:'sm',
            height:'155',
            cols: [[
                {field: 'index_num',width:40, title: '序号'},
                {field: 'heart_rate',width:80, title: '心率',sort:true},
                {field: 'blood_pres',width:120, title: '血压',sort:true,templet:function(d){
                  var blood_pres='0'
                  if(d.blood_pres!='0'){
                    blood_pres=eval('('+d.blood_pres+')')
                    blood_pres='高：'+blood_pres['h_pres']+','+'低：'+blood_pres['l_pres']
                  }
                  return blood_pres
                }},
                {field: 'temp',width:80, title: '温度',sort:true},
                {field: 'step_count',width:80, title: '步数',sort:true},
                {field: 'dirct',width:80, title: '方向',sort:true},
                {field: 'speed',width:80, title: '速度',sort:true},
                {field: 'serv_receive',width:140, title: '时间',sort:true},
                {field: 'location',title: '位置',templet:function(d){
                  
                  if(d.lng==0 | d.lng=='0'){
                    return '地址为空'
                  }else{
                    return '<a id="trail'+d.id+'" class="layui-btn layui-btn-primary layui-btn-xs" onclick="show_trail_location('+d.lng+','+d.lat+',\''+d.device_id+'\','+d.id+')">'+d.lng+'，'+d.lat+'</a>'
                  }
                  return d.lng+'，'+d.lat
                }},
            ]],
            limit:10000000
            // page: false
          });

}

table.on('row(interact_detail_table)',function(obj){
  open_infowindow(obj.data)
})

var show_trail_location=function(lng,lat,dev_id,trail_id){
  console.log(lng,lat,dev_id)
  var point=new BMap.Point(lng,lat)
  gps_location(point,dev_id)
  setTimeout(function(){
    $('#trail'+trail_id).text(postion_all[dev_id])
  },500)

}

  // 百度地图调用
var fugaiwu=new Array();
var hard_info;
var mylabel;
var marker;
var map = new BMap.Map("allmap");    // 创建Map实例
map.centerAndZoom(new BMap.Point(114.098014, 22.712257), 12);  // 初始化地图,设置中心点坐标和地图级别
//添加地图类型控件
map.addControl(new BMap.MapTypeControl({
  mapTypes:[
          BMAP_NORMAL_MAP,
          BMAP_HYBRID_MAP
      ]}));   
map.setCurrentCity("北京");          // 设置地图显示的城市 此项是必须设置的
map.enableScrollWheelZoom(true);
map.enableAutoResize();
var geoc = new BMap.Geocoder();  


var addmaker=function(gps){
  var myIcon
  myIcon = new BMap.Icon("/static/device_icon/track_button.png", new BMap.Size(72,144),{anchor : new BMap.Size(15, 33),imageSize:new BMap.Size(22, 30)});
  var point,gps_lng,gps_lat;
  point=new BMap.Point(gps.lng,gps.lat)
  marker = new BMap.Marker(point,{icon:myIcon});
  map.addOverlay(marker);//加载定位点
  marker.setTitle(gps.device_id);//设置标题
  var lb_html='<button class="layui-btn layui-btn-sm" style="border-radius:10px">'+gps.user_name+'</button>'
  var pt_label=new BMap.Label(lb_html,{offset:new BMap.Size(-18,-35)});
  pt_label.setStyle({border:'0',borderRadius:"10px"})
  marker.setLabel(pt_label);
  marker.dev_datail=gps.dynamic
  marker.addEventListener('click', function (e) {
    open_infowindow(e.target.dev_datail)
  })
  return marker
};


var postion_all=new Array;
var trail_locations=new Array;

//轨迹回放用的坐标转中文地址计算
var trail_location=function(pt,mesg_receive){
      var location
      geoc.getLocation(pt, function(rs){
      var addComp = rs.address
      if(rs.surroundingPois.length!=0){
         location=addComp+','+rs.surroundingPois[0]['title']
         trail_locations[mesg_receive]=location;
      }else{
         location=addComp
         trail_locations[mesg_receive]=location;
      }
    });
    };
//地图定位图标用的坐标转中文地址计算
var marker_title;
var gps_location=function(pt,gps_id){
      var location
      geoc.getLocation(pt, function(rs){
      console.log(rs)
      var addComp = rs.address
      if(rs.surroundingPois.length!=0){
         location=addComp+','+rs.surroundingPois[0]['title']
         postion_all[gps_id]=location;
           
      }else{
         location=addComp
         postion_all[gps_id]=location;
      }
    });
    };

//信息窗口
var open_infowindow=function(tp){
  var blood_pres=''
  if(tp.blood_pres!='0'){
    blood_pres=eval('('+tp.blood_pres+')')
    blood_pres=blood_pres['h_pres']+'/'+blood_pres['l_pres']
  }
  //信息窗口参数
  var opts = {
    width : 10,     // 信息窗口宽度
    height: 80,     // 信息窗口高度
    };

  marker_title=
    "<div style=''>"+
      '<i class="layui-icon" type="button" onclick="close_marker_lable()" style="margin: 0px 0px 0px 85%;">&#x1006;</i>'+
      "<table class='layui-table' lay-size='sm' lay-skin='nob' style='margin:0;padding:0;border-radius:20px'>"+
        "<tr>"+
          "<td>"+
            "<i class='fa fa-heartbeat' aria-hidden='true' style='color: red;'></i>："+tp.heart_rate+"次/min"+
          "</td>"+
          "<td>"+
            "<i class='fa fa-thermometer-empty'  style='color:#FFB800'></i>："+''+"C°"+
          "</td>"+
        "</tr>"+
        "<tr>"+
          "<td>"+
           " <i class='fa fa-stethoscope' aria-hidden='true' style='color: blue;'></i>："+blood_pres+
          "</td>"+
          "<td>"+
            "<i class='fa fa-blind' aria-hidden='true' style='color:#5FB878'></i>："+tp.step_count+"步"+
          "</td>"+
        "</tr>"+
        "<tr>"+
         "<td>"+
            "<i class='fa fa-compass' aria-hidden='true' style='color:#5FB878'></i>："+tp.dirct+"°"+
          "</td>"+
          "<td>"+
            "<i class='fa fa-hourglass'  style='color:#FFB800'></i>："+tp.speed+"km/h"+
          "</td>"+
        "</tr>"+
        "<tr>"+
          "<td>"+
            " <i class='fa fa-map-marker' aria-hidden='true' style='color:#5FB878'></i>："+tp.track_type+
          "</td>"+
        "</tr>"+
        "<tr>"+
          "<td colspan='2'>"+
            "<i class='layui-icon layui-icon-console' aria-hidden='true' style='color:#1E9FFF'></i>："+tp.serv_receive+
          "</td>"+
        "</tr>"+
      "</table>"+
    "</div>"
  ;

  // var marlb=new BMap.Label(marker_title,{offset:new BMap.Size(20,-150)});
  var marlb=int_marker.getLabel()
  // map.removeOverlay(marlb);
  marlb.setStyle({border:'2px',borderRadius:"20px",borderColor:'#F2F2F2',display:''})
  marlb.setOffset(new BMap.Size(20,-150))
  marlb.setContent(marker_title)
  int_marker.setLabel(marlb)   
};
var close_marker_lable=function(){
  var marlb=int_marker.getLabel()
  marlb.setStyle({display:'none'})
}


// ------即时交互PLAY ------//
var wsocket={'start':false};
var trail_opt={};
var chosed_dev;
var int_marker;
trail_opt['play_speed']=parseInt($('#play_speed').val())

form.on('submit(trail_query)',function(obj){
  var dev_msg=[];
  var dev_num=1;
  if(obj.field.device_id!==''){
    var dev=get_detail_from_id(device,obj.field.device_id)
    // 把选中设备赋值为该页面的全局变量，随时调用
    chosed_dev=dev
    $('.layui-body').attr('style','padding:0px;bottom:160px;left:0px')
    $('.layui-footer').attr('style','height:160px')
    $('.layui-footer').show()
    $('.layui-side').hide()
    console.log(chosed_dev)
    add_dev_detail(dev)
    dev.dynamic.lng=dev.lng;
    dev.dynamic.lat=dev.lat
    dev.dynamic.index_num=1
    dev_msg.push(dev['dynamic'])
    interact_table(dev_msg)
    map.clearOverlays()
    int_marker=addmaker(dev)
    var pos=new BMap.Point(dev.lng,dev.lat)
    map.panTo(pos);

    if(chosed_dev.on_off_line!=='online'){
        layer.msg('设备离线，无法执行该指令')
        return false
      }

    show_hide_chat_panle('show',dev.user_name)
    
    // 连接websocket

    if('WebSocket' in window){
      $('#start_interact').click(function(){
        var wsurl="wss://www.jyttracker.com/websocket/"
        if(window.location.host=='127.0.0.1'){
          wsurl="ws://127.0.0.1:8000/interact/"
        }
        wsocket = new WebSocket(wsurl);
        wsocket.onopen = function () {
            layer.msg('实时交互start');//成功连接上Websocket
            wsocket.send(obj.field.device_id);//发送数据到服务端
        };
        wsocket.onclose = function () {
            layer.msg('实时交互end');
            // wsocket=''
        };
        wsocket.onmessage = function (e) {
          console.log('message: ' + e.data);//打印服务端返回的数据
          if(e.data=='websocket end'){
            wsocket.close()
        }
          else{
            var rece_data=eval('('+e.data+')')
            var newest=rece_data['dynamic']
            var m_data=rece_data['media']

          if(m_data!='no_change'){
            var div_posi='left'
            var media_data=m_data.content
            var kind=m_data.content_kind
            var send_time=m_data.send_time
            fill_chat_panle(media_data,kind,send_time,chat_p_w,$('#chat_content_panle'),div_posi)
          }

          if(newest!='no_change'){
            layer.msg('有新消息')
            if(newest.lng!='0' && newest.lng!=0){
              var track_line_point=[];
              track_line_point.push(pos)
              track_line_point.push(new BMap.Point(newest.lng,newest.lat))
              marker_move(track_line_point,int_marker)
              pos=new BMap.Point(newest.lng,newest.lat)
            }
            newest.index_num=dev_num+1
            dev_num++
            dev_msg.unshift(newest)
            interact_table(dev_msg)
          } 
        }
      };
    })

      $('#stop_interact').click(function(){
        wsocket.send('stop_websocket');//发送数据到服务端
      })
    }else{
      layui.msg('浏览器不支持该功能')
    }

  }
  trail_param=JSON.stringify(obj.field)
  console.log(trail_param)
   // $.ajax({
   //        type: 'POST',
   //        url:"/trail/?what="+'get_trail',
   //        data:{trail_param},
   //        async:true,
   //        dataType: 'json',
   //        success: function( hard_info) {
            
   //          console.log(hard_info)
   //          var tarckpoint=new Array();
   //          var trackinfo=new Array();

   //          if(hard_info.length==0){
   //            layer.msg('该时间段没有轨迹数据');
   //            return false;
   //          };
   //          // 清除之前的覆盖物
   //          map.clearOverlays()
   //          //轨迹点封装
   //          trail_opt['point_order']={}

   //          for(var i=0;i<hard_info.length;i++){
   //            var point_len=hard_info.length
   //            var point_order=(Math.round((1/point_len)*100))*i+'%'
   //            var lng=hard_info[i]['lng']
   //            var lat=hard_info[i]['lat']
   //            var newxy=wgs2bd(lat,lng);
   //            var pt_trail = new BMap.Point(newxy[1],newxy[0]);
   //            pt_trail['html']='<div>'+hard_info[i]['serv_receive']+','+hard_info[i]['speed']+'公里/小时</div>'
   //            pt_trail['dev_datail']=hard_info[i]
   //            trail_opt['point_order'][point_order]=pt_trail
   //            trail_location(pt_trail,hard_info[i]['serv_receive'])
   //            tarckpoint.push(pt_trail);
   //            trackinfo.push(hard_info[i]);
   //          };
   //          var trail_points_show = new BMap.PointCollection(tarckpoint, {size: BMAP_POINT_SIZE_NORMAL,shape: BMAP_POINT_SHAPE_CIRCLE,
   //          color: 'blue'});
   //          trail_points_show.addEventListener('click', function (e) {
   //            open_infowindow(e.point.dev_datail,e.point)
   //          })
   //          map.addOverlay(trail_points_show)

   //          trail_opt['tarckpoint']=tarckpoint
   //          trail_opt['status']='f_run'
   //          trail_opt['current_pt']=0
   //          carMk=addmaker(hard_info[0])
   //          trail_opt['carMk']=carMk
   //          // console.log(tarckpoint)
            
   //          start_Icon = new BMap.Icon("/static/img/start.png", new BMap.Size(100,60),{anchor : new BMap.Size(15, 33),imageSize:new BMap.Size(28, 30)});
   //          end_Icon = new BMap.Icon("/static/img/end.png", new BMap.Size(100,60),{anchor : new BMap.Size(15, 33),imageSize:new BMap.Size(28, 30)});
   //          var endpoint=new BMap.Point(tarckpoint[tarckpoint.length-1].lng,tarckpoint[tarckpoint.length-1].lat);
   //          var startpoint=new BMap.Point(tarckpoint[0].lng,tarckpoint[0].lat);
   //          var startmarker = new BMap.Marker(startpoint,{icon:start_Icon});
   //          var endmarker=new BMap.Marker(endpoint,{icon:end_Icon});
   //          // var startlabel=new BMap.Label("起点",{offset:new BMap.Size(20,-10)});
   //          // var endlabel=new BMap.Label("终点",{offset:new BMap.Size(20,-10)});
   //          // startmarker.setLabel(startlabel);
   //          // endmarker.setLabel(endlabel);
   //          startmarker.setTitle('start');
   //          endmarker.setTitle('end');
   //          map.addOverlay(startmarker); 
   //          map.addOverlay(endmarker); 
   //          var polyline = new BMap.Polyline(tarckpoint, {strokeColor:"blue", strokeWeight:5, strokeOpacity:0.6});
   //          map.addOverlay(polyline);
   //          map.setViewport(tarckpoint);
   //    }
   //  })
  });

// ------即时交互STOP ------//

var marker_move=function(pts,carMk) {
  var initPos=pts[0];
  var targetPos=pts[1];
  var st_p=pts[0];
  // 获取两点距离
  function _getDistance(pxA, pxB) {
      return Math.sqrt(Math.pow(pxA.x - pxB.x, 2) + Math.pow(pxA.y - pxB.y, 2));
  };
  // wgs84坐标转换为墨卡托坐标
  function _getMercator(poi) {
      return map.getMapType().getProjection().lngLatToPoint(poi);
  };
  // 未知,大概是平滑滤波之类,确保移动的平滑.
  function effect(initPos, targetPos, currentCount, count) {
    var b = initPos, c = targetPos - initPos, t = currentCount,
    d = count;
    return c * t / d + b;
  }
    //当前的帧数
    currentCount = 0;
    //步长，米/秒
    timer = 10;
    step = 100 / timer;
    //初始坐标
    init_pos = map.getMapType().getProjection().lngLatToPoint(initPos);
    //获取结束点的(x,y)坐标
    target_pos = map.getMapType().getProjection().lngLatToPoint(targetPos);
    //总的步长
    count = Math.round(_getDistance(init_pos, target_pos) / step);

  intervalFlag = setInterval(function() {
  //两点之间当前帧数大于总帧数的时候，则说明已经完成移动
      if (currentCount >count | count < 1) {
          clearInterval(intervalFlag);
      }else {
              currentCount++;
              var x = effect(init_pos.x, target_pos.x, currentCount, count),
                  y = effect(init_pos.y, target_pos.y, currentCount, count),
                  pos = map.getMapType().getProjection().pointToLngLat(new BMap.Pixel(x, y));
              // 设置marker
              if(currentCount == 1){
                  var pt_label=carMk.getLabel()
                  pt_label.setContent(initPos['html']);
                  carMk.setLabel(pt_label);
                  if(!map.getBounds().containsPoint(pos)){
                    map.panTo(pos);
                  } 
              }
              //正在移动
              var move_line_p=[]
              move_line_p.push(st_p)
              move_line_p.push(pos)
              var m_line=new BMap.Polyline(move_line_p, {strokeColor:"blue", strokeWeight:5, strokeOpacity:0.6});
              map.addOverlay(m_line);
              carMk.setPosition(pos);
              st_p=pos
              //设置自定义overlay的位置
          }
  },timer);
};

// 播放轨迹
$("#run").click(function(){
  console.log('run====>')
  var pts=trail_opt['tarckpoint']
  var carMk=trail_opt['carMk']
  var point_num=pts.length
  var ii=0
  // map.setZoom(17)
  // 从百度第三方开源库LUSHU路书源码摘出图标移动部分，做了适应修改
// 停止状态和首次运行状态，启动轨迹
  if(trail_opt['status']=='f_run' | trail_opt['status']=='stop'){
    trail_opt['status']='run';
    trail_opt['current_pt']=0
    marker_move(ii)
// 正在运行轨迹的状态，点击play无效
  }else if(trail_opt['status']==='run'){
    return
// 按下暂停，记录暂停状态，再点击播放，从暂停处开始播放
  }else{
    if(trail_opt['current_pt']>=point_num){
      trail_opt['current_pt']=0
    }
    trail_opt['status']='run'
    marker_move(trail_opt['current_pt'])
  }
// 递归判断条件，上一个点移动完毕，判断是否还有下一个点需要移动
  var move_next=function(num){
    if(num <= point_num-2 && trail_opt['status']=='run'){
      marker_move(num)
    }else{
      ii=0;
      if(trail_opt['current_pt']>=point_num-2){
      trail_opt['current_pt']=0
      }
      trail_opt['status']='stop'
      setSlider((1), 'trail_progress');
    }
  }
    
});
// 暂停
$("#pause").click(function(){
  trail_opt['status']='pause'
  console.log(trail_opt)
});
// 停止
$("#stop").click(function(){
  trail_opt['status']='stop'
  setSlider(0,'trail_progress')
});

// 加快播放速度
$("#add_play_speed").click(function(){

  trail_opt['play_speed']=trail_opt['play_speed']+200
  if (trail_opt['play_speed']>1400){
    trail_opt['play_speed']=1400
  }

  form.val('trail_query_form',{'play_speed':trail_opt['play_speed'].toString()})
});
// 降低播放速度
$("#prev_play_speed").click(function(){
  trail_opt['play_speed']=trail_opt['play_speed']-200
  if (trail_opt['play_speed']<200){
    trail_opt['play_speed']=200
  }
  form.val('trail_query_form',{'play_speed':trail_opt['play_speed'].toString()})
});


//添加选择设备列表
$(function(){ 
  $('#tml_list').empty()

  $('#tml_list').append('<option value="">选择/搜索设备</option>')
  
  for (var i = device.length - 1; i >= 0; i--) {
    var user_name=device[i]['user_name'];
    if(device[i]['user_detail']!='0'){
      user_name=device[i].user_detail.name
    }
    var option='<option value="'+device[i].device_id+'">'+user_name+'</option>'
    if(chosed_dev.device_id==device[i].device_id){
      option='<option value="'+device[i].device_id+'" selected="">'+user_name+'</option>'
    }
    $('#tml_list').append(option)
  }
    form.render()
}); 

laydate.render({
  elem: '#chat_history_time'
  ,type: 'datetime'
  ,range: true
});

// 地图控件
var navigationControl = new BMap.NavigationControl({
    // 靠左上角位置
    anchor: BMAP_ANCHOR_TOP_RIGHT,
    offset: new BMap.Size(10, 60), //偏离值
    // LARGE类型
    type: BMAP_NAVIGATION_CONTROL_LARGE,
    // 启用显示定位
    enableGeolocation: true
  });
  map.addControl(navigationControl);
  // 添加定位控件

var show_self_addr = new BMap.GeolocationControl();
  show_self_addr.addEventListener("locationSuccess", function(e){
    // 定位成功事件
    var address = '';
    address += e.addressComponent.province;
    address += e.addressComponent.city;
    address += e.addressComponent.district;
    address += e.addressComponent.street;
    address += e.addressComponent.streetNumber;
    layer.msg("当前定位地址为：" + address);
  });
  show_self_addr.addEventListener("locationError",function(e){
    // 定位失败事件
    layer.msg(e.message);
  });
  map.addControl(show_self_addr);






</script>

